package com.ssps.front.tenant2.controller2;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssps.entity.*;
import com.ssps.front.tenant2.service2.Tenant2Service;
import com.ssps.front.tenant2.utils2.Tenant2Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: peng
 */
@Controller
@RequestMapping("tenant2")
public class Tenant2Controller {
    @Autowired
    Tenant2Service tenant2Service;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 抢租客进入页面查看发布的所有出租信息
     *
     * @return
     */
    @RequestMapping("list")
    @ResponseBody
    public Map<String, Object> selectRentParkingInfo(@RequestBody String body , HttpSession session) {
        Map<String, Object> map = new HashMap<>();


        try {
            Map<String,Object> resultMap = tenant2Service.selectRentParkingInfo(body);
            List<Orders> orders = (List<Orders>) resultMap.get("orders");
            User loginUser = (User) session.getAttribute("loginUser");

            for(int i = 0 ; i < orders.size() ; i++){
                Integer pid = orders.get(i).getParking().getPid();
                Boolean hasLike = redisTemplate.opsForValue().getBit("parking:" + pid, loginUser.getUid() * 10);

                orders.get(i).getParking().setHasLike(hasLike);
            }
            PageInfo<Orders> pageInfo = (PageInfo<Orders>) resultMap.get("pageInfo");
            map.put("result", true);
            map.put("orders", orders);
            map.put("pageInfo", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", true);
        } finally {
            return map;
        }
    }

    /**
     * 抢租客修改密码前获取验证码
     *
     * @return
     */
    @RequestMapping("getConCode")
    @ResponseBody

    public Map<String, Object> getConCode(@RequestBody String phone) {
        Map<String, Object> map = new HashMap<>();

        try {
            Map<String, String> parse = Tenant2Utils.parse(phone);
            String code = tenant2Service.Sendsms(parse.get("phone"));
            redisTemplate.opsForValue().set(parse.get("phone"), code, 80, TimeUnit.SECONDS);
            map.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", false);
        } finally {
            return map;
        }
    }

    /**
     * 抢租客确认验证码是否正确
     *
     * @return
     */
    @RequestMapping("confirm_code")
    @ResponseBody
    public Map<String, Object> confirm_code(@RequestBody String body, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        Integer flag = 200;
        try {
            Map<String, String> parse = Tenant2Utils.parse(body);
            User loginUser = (User) session.getAttribute("loginUser");
            String code = (String) redisTemplate.opsForValue().get(loginUser.getPhone());
            /**
             * 验证码错误或是无效，则返回210
             */
            System.out.println(code);
            System.out.println(parse.get("code"));
            if (code == null || code.equals("") || !code.equals(parse.get("code"))) {
                flag = 210;
            } else {
                /**
                 * 正确返回：200
                 */
                flag = 200;
            }

        } catch (Exception e) {
            e.printStackTrace();
            /**
             * 出现异常返回：220
             */
            flag = 220;

        } finally {
            map.put("result", flag);
            return map;
        }
    }


    /**
     * 抢租客修改密码
     *
     * @return
     */
    @RequestMapping("updateTenant2Key")
    @ResponseBody
    public Map<String, Object> updateTenant2Key(@RequestBody String body, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        Integer flag = 200;
        try {
            Map<String, String> parse = Tenant2Utils.parse(body);
            User loginUser = (User) session.getAttribute("loginUser");

            String oldpwd = parse.get("oldpwd");
            /**
             * 输入的原密码与实际原密码不符 flag=200
             */
            if (!loginUser.getPwd().equals(Tenant2Utils.getMD5(oldpwd, loginUser.getSalt()))) {
                flag = 210;
            } else {
                /**
                 * 修改成功：200
                 */
                String salt = Tenant2Utils.getSalt();
                String password = Tenant2Utils.getMD5(parse.get("password"), salt);
                loginUser.setSalt(salt);
                loginUser.setPwd(password);
                tenant2Service.update(loginUser);
                flag = 200;
                /**
                 * 密码修改成功销毁session
                 */
                session.invalidate();
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = 220;
        } finally {
            map.put("result", flag);
            return map;
        }
    }

    /**
     * 确认符合抢租条件
     *
     * @param oid
     * @param session
     * @return
     */
    @RequestMapping("confirmInfo")
    @ResponseBody
    public Map<String, Object> confirmInfo(@RequestBody String oid, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        try {
            Map<String, String> parse = Tenant2Utils.parse(oid);
            UserInfo userInfo = (UserInfo) session.getAttribute("loginUserInfo");
            Map<String, Object> result = tenant2Service.confirmInfo(Integer.parseInt(parse.get("oid")), userInfo);

            map.put("bogo", result.get("bogo"));
            map.put("has", result.get("has"));
            map.put("coupons", result.get("coupons"));
        } catch (Exception e) {
            e.printStackTrace();
            /**
             * 出现异常400
             */
            map.put("bogo", 400);
        } finally {
            return map;
        }
    }

    /**
     * 抢租客抢车位,并从账户支付资金
     *
     * @param body
     * @param session
     * @return
     */
    @RequestMapping("updateGetParking")
    @ResponseBody
    public Map<String, Object> updateGetParking(@RequestBody String body, HttpSession session) {

        Map<String, Object> map = new HashMap<>();
        Integer bogo = 200;

        try {
            Map<String, String> parse = Tenant2Utils.parse(body);
            Boolean flag = redisTemplate.opsForValue().setIfAbsent("lock", "1", 10, TimeUnit.SECONDS);
            while (!flag) {
                try {
                    TimeUnit.MICROSECONDS.sleep(5);
                    flag = redisTemplate.opsForValue().setIfAbsent("lock", "1", 10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        redisTemplate.expire("lock", 10, TimeUnit.SECONDS);
                    }
                }
            });

            th.setDaemon(true);
            th.start();

            String stock = (String) redisTemplate.opsForValue().get("order:" + parse.get("rid"));

            Integer num = Integer.parseInt(stock);
            System.out.println(num);
            if (num > 0) {
                num--;
                redisTemplate.opsForValue().set("order:" + parse.get("rid"), num + "");
                redisTemplate.opsForValue().set("order:2", num + "");

                /**
                 * 修改订单状态，并从账户支付，抢租客账户资金减少，平台账户资金增加，若使用卡券，则添加ucid
                 */
                Orders order = tenant2Service.selectOrders(Integer.parseInt(parse.get("rid")));
                UserInfo userInfo = (UserInfo) session.getAttribute("loginUserInfo");
                if(parse.get("ucid") != null && !parse.get("ucid").equals("")){
                    order.setUcid(Integer.parseInt(parse.get("ucid")));
                }
                /**
                 * 抢到 支付正常200
                 * 出了bug 300
                 * 账户金额小于定价 100
                 */
                bogo = tenant2Service.updateGetParking(order, userInfo.getUiid());
            } else {
                /**
                 * 没抢到 210
                 */
                bogo = 210;
                redisTemplate.delete("order:" + parse.get("rid"));

            }
        } catch (NumberFormatException e) {
            /**
             * 出了异常 220
             */
            bogo = 220;
            e.printStackTrace();
        } finally {
            redisTemplate.delete("lock");

            map.put("bogo", bogo);
            return map;
        }
    }


    /**
     * 抢租客充值
     *
     * @param bodys
     * @param resp
     * @param req
     */
    @RequestMapping("top_up")
    public void topUp2(@RequestBody String bodys, HttpServletResponse resp, HttpServletRequest req) {


        try {

            Map<String, String> parse = Tenant2Utils.parse(bodys);

            //生成订单信息
            UserInfo loginUserInfo = (UserInfo) req.getSession().getAttribute("loginUserInfo");
            User loginUser = (User) req.getSession().getAttribute("loginUser");
            String subject = "用户充值";
            String body = "充值";
            /**
             * 使用UUID随机生成一个充值码
             */
            String out_trade_no = UUID.randomUUID().toString().replace("-", "") + "x" + loginUserInfo.getUiid();
            /**
             * 放入充值的总额
             */
            String total_amount = parse.get("money");
            Map<String, Object> paramMap = new HashMap<>();
            /**
             * 存入条件
             */
            paramMap.put("loginUserInfo", loginUserInfo);
            paramMap.put("subject", subject);
            paramMap.put("body", body);
            paramMap.put("out_trade_no", out_trade_no);
            paramMap.put("total_amount", total_amount);

            String result = tenant2Service.top_up(req, resp, paramMap);

            if (result != null) {
                PrintWriter writer = resp.getWriter();
                writer.write(result);
                writer.flush();
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付成功后，修改userinfo的余额信息
     *
     * @param response
     * @param request
     */
    @RequestMapping("success")
    @ResponseBody
    public void success(HttpServletResponse response, HttpServletRequest request) {
        String total_amount = request.getParameter("total_amount");
        String out_trade_no = request.getParameter("out_trade_no");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        String str = "<h1>充值成功！！！</h1>";
        str += "<h2>交易金额：￥" + total_amount + "</h2>";
        str += "<h2>交易编号：" + out_trade_no + "</h2>";
        str += "<h2>关闭当前页面，继续操作</h2>";
        str += "<a href='javascript:void(0)' onclick='jump()'>返回原页面</a>";
        str += "<script>";
        str += "function jump(){location.href=\"http://localhost:63342/ssps/vue/tenant/index2.html?NN=1\"};";

//        str += "var tempwindow=window.open('_blank');";
//        str += "tempwindow.location.href='http://localhost:63342/ssps/vue/tenant/index2.html';";
//        str += "var form = document.createElement('form');";
//        str += "form.action = 'http://localhost:63342/ssps/vue/tenant/index2.html';";
//        str += "form.target = '_blank';";
//        str += "form.method = 'POST';";
//        str +=  "var btn = '<button>返回原页面</button>';";
//        str += "form.innerHTML = btn;";
//        str += "document.body.appendChild(form);";

        str += "</script>";
        try {
            writer = response.getWriter();
            writer.print(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush();
            writer.close();
        }

    }

    /**
     * 支付成功修改状态
     * @param response
     * @param request
     */
    @RequestMapping("notify")
    @ResponseBody
    public void notify(HttpServletResponse response, HttpServletRequest request) {
        String total_amount = request.getParameter("total_amount");
        String out_trade_no = request.getParameter("out_trade_no");


        String uuid = out_trade_no.substring(out_trade_no.lastIndexOf("x") + 1);
        tenant2Service.updateUserInfoBalance(Integer.parseInt(uuid), total_amount);
    }

    /**
     * 抢租客首页查看评论
     * @param body
     * @return
     */
    @RequestMapping("lookComments")
    @ResponseBody
    public Map<String,Object> lookComments(@RequestBody String body){
        Map<String,Object> map = new HashMap<>();
        try{
            Map<String, String> parse = Tenant2Utils.parse(body);
            PageHelper.startPage(Integer.parseInt(parse.get("pageNum")),6);
            List<Comment> comments = tenant2Service.lookComments(Integer.parseInt(parse.get("pid")));
            PageInfo<Comment> pageInfo = new PageInfo<>(comments);
            map.put("pageInfo",pageInfo);
            map.put("result",true);
        }catch (Exception e){
            map.put("result",false);
        }finally {
            return map;
        }
    }
    @RequestMapping("like")
    @ResponseBody
    public Map<String,Object> like(@RequestBody String body,HttpSession session){
        Map<String,Object> map = new HashMap<>();
        try{
            Map<String, String> parse = Tenant2Utils.parse(body);
            User loginUser = (User) session.getAttribute("loginUser");
            if(redisTemplate.opsForValue().getBit("parking:"+parse.get("pid"),loginUser.getUid()*10)){
                redisTemplate.opsForValue().setBit("parking:"+parse.get("pid"),loginUser.getUid()*10,false);
                map.put("hasLike",false);
            }else{
                redisTemplate.opsForValue().setBit("parking:"+parse.get("pid"),loginUser.getUid()*10,true);
                map.put("hasLike",true);
            }
            map.put("result",true);
        }catch (Exception e){
            e.printStackTrace();
            map.put("result",false);
        }finally {
            return map;
        }
    }
}
